import { useRoute, useRouter } from 'vue-router'
import { useNavStore } from '@/store/nav'

export function useBack(viewerRouter, emitFn, routeName, excludeRoute = []) {
  const route = useRoute()
  const router = useRouter()

  const navStore = useNavStore()
  const { toHome, toSearch } = navStore

  const { currIndex, prev } = viewerRouter

  return () => {
    if (currIndex.value > 0) {
      prev()
      return
    }

    // currIndex 已經為 0
    if (routeName && route.name.indexOf(routeName) !== -1 && !excludeRoute.some((name) => route.name.includes(name))) {
      const { from = 'home' } = route.query
      if (from === 'home') {
        toHome()
      } else if (from === 'search') {
        toSearch()
      } else {
        router.replace({ name: from })
      }
    } else {
      emitFn()
      prev()
    }
  }
}
